;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.PurchaseInvoiceApply", [])
        .controller("PurchaseInvoiceApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            var btnPermissionCode = {
                purchaseAdd: window.ActionCode.purchaseAdd,
                purchaseEdit: window.ActionCode.purchaseEdit,
                purchaseDel: window.ActionCode.purchaseDel,
                purchaseAudit: window.ActionCode.purchaseAudit,
                purchaseInvoicerExport: window.ActionCode.purchaseInvoicerExport,
                purchaseInvoicerExportAll: window.ActionCode.purchaseInvoicerExportAll,
            };
            
            $scope.btnPermission = {
                purchaseAdd: true,
                purchaseEdit: true,
                purchaseDel: true,
                purchaseAudit: true,
                purchaseInvoicerExport: true,
                purchaseInvoicerExportAll: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.activeFlag = [true, false, false, false];

            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.tableConfig = {
                scrollWidth: 1600,
                tableCol: [{
                        name: "开票申请单号",
                        dataField: "purchaseInvoiceOrder",
                        width: 165,
                        type: "click",
                        isShow: true,
                        toSort: false,
                    },
                    {
                        name: "供货商代码",
                        dataField: "supplierOrgid",
                        width: 140,
                        isShow: true,
                        toSort: false,
                        isFixed: false,
                    },
                    {
                        name: "供货商名称",
                        dataField: "supplierName",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "开票总金额",
                        dataField: "invoicePrice",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "已申请付款金额",
                        dataField: "applyPrice",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "状态",
                        dataField: "status",
                        width: 170,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "申请人",
                        dataField: "applyName",
                        width: 160,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "申请日期",
                        dataField: "applyTime",
                        width: 130,
                        isShow: true,
                        toSort: false
                    }
                ]
            };

            $scope.dataList = [];
            $scope.toolbarConfig = {};
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchaseInvoiceApply/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/purchaseInvoiceApply/exportAll")
            };
            $scope.condition = {
                invoiceNo: null,
                invoicePaperNo: null,
                status: '',
                payerOrgName: null,
                createDateStart: null,
                createDateEnd: null
            };

            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (item) {
                    item = false;
                });
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {

                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };

            /**
             * 开票申请 - 全选
             */
            $scope.orderSelectAll = function () {
                if ($scope.orderObj.purchaseOrgId == undefined) {
                    $scope.markInfo.allChecked = false;
                    return;
                }
                if (!$scope.markInfo.allChecked) {
                    for (var item of  $scope.orderDataList) {
                        item.isChecked = false;
                        delSelectedItem(item);
                    }
                    return;
                }

                var params = [];
                for (var item of  $scope.orderDataList) {
                    var paramObj = {
                        id: item.id,
                        purchaseBillNo: item.purchaseBillNo,
                        materialNo: item.materialNo,
                        rowNo: item.rowNo,
                        supplierOrgId: $scope.orderObj.purchaseOrgId
                    };
                    params.push(paramObj)
                }
                judgeProvisionalPrice(params).then(function (data) {
                    if (!data) {
                        return;
                    }

                    var provisionalPriceFlag = false;
                    for (var item of $scope.orderDataList) {
                        if (!data[item.id] && data[item.id] !=0) {
                            item.isChecked = false;
                            provisionalPriceFlag = true;
                        } else {
                            item.price = data[item.id]; // 更新价格

                            item.isChecked = true;
                            var index = $scope.orderObj.materialList.findIndex((function (obj) { return obj.id == item.id }))
                            if (index == -1) {
                                $scope.orderObj.materialList.push(item)
                            }
                        }
                    }
                    if (provisionalPriceFlag) {
                        ybWidget.ShowMessage('暂估价不允许开票，已过滤掉不符合条件的项。');
                    }
                })
            };

            /**
             *  开票申请 - 复选框
             */
            $scope.orderSelectSingle = function (item) {
                if (!item.isChecked) {
                    delSelectedItem(item);
                    return;
                }

                var paramObj = {
                    id: item.id,
                    purchaseBillNo: item.purchaseBillNo,
                    materialNo: item.materialNo,
                    rowNo: item.rowNo,
                    supplierOrgId: $scope.orderObj.purchaseOrgId
                };
                judgeProvisionalPrice([paramObj]).then(function (data) {
                    if (!data) {
                        return;
                    }
                    if (!data[item.id] && data[item.id] !=0) {
                        item.isChecked = false;
                        ybWidget.ShowMessage('暂估价不允许开票');
                        return;
                    }
                    item.price = data[item.id]; // 更新价格

                    $scope.orderObj.materialList.push(item);
                    $scope.markInfo.allChecked = checkAll($scope.orderDataList);
                })
            };

            function judgeProvisionalPrice(data) {
                var service = "device";
                var reqUrl = "/purchaseInvoiceApply/queryProvisional";
                return ybHttp.Post(service, reqUrl, {resInvoiceApplyList: data}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value || {};
                });
            }

            /**
             * 删除右侧已选中的列表
             */
            function delSelectedItem(obj) {

                var index = $scope.orderObj.materialList.findIndex((function (item) {
                    return item.id == obj.id
                }))
                if (index != -1) {
                    $scope.orderObj.materialList.splice(index, 1)
                }
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {}
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            /**
             *  本次开票数量改变
             *  触发方法
             *
             */
            $scope.checkStock = function (obj) {
                if ($scope.orderObj.isEdit) {
                    if (obj.invoiceNum > obj.allowNum + obj.invoicesIssued) {
                        alert("本次开票数量 不能大于 总开票数量");
                        obj.invoiceNum = null;
                        obj.currentMoney = 0;
                    } else {
                        if (obj.type == "退货出库单") {
                            obj.currentMoney = (obj.invoiceNum * obj.price * -1).toFixed(2);
                        } else {
                            obj.currentMoney = (obj.invoiceNum * obj.price).toFixed(2);
                        }
                        getAllMoney();
                    }
                } else {
                    if (obj.invoiceNum > obj.allowNum) {
                        alert("本次开票数量 不能大于 可开票数量");
                        obj.invoiceNum = null;
                        obj.currentMoney = 0;
                        return;
                    } else {
                        if (obj.type == "退货出库单") {
                            obj.currentMoney = (obj.invoiceNum * obj.price * -1).toFixed(2);
                        } else {
                            obj.currentMoney = (obj.invoiceNum * obj.price).toFixed(2);
                        }
                        getAllMoney();
                    }
                }
            };

            /**
             *  计算申请开票总金额
             *  totalSum
             *  $scope.orderObj.materialList
             */
            function getAllMoney() {
                $scope.orderObj.totalSum = 0;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    if (item.type == '退货出库') {
                        $scope.orderObj.totalSum -= Number(item.currentMoney);
                    } else {
                        $scope.orderObj.totalSum += Number(item.currentMoney);
                    }
                });
            };

            /**
             *  删除已选择的列表
             */
            $scope.delSelectItem = function (obj, index) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    $scope.orderObj.materialList.splice(index, 1);
                    getAllMoney();
                })

            };

            function getDataList(curPage) {
                $scope.markInfo.curRow = -1;
                var service = "device";
                var reqUrl = "/purchaseInvoiceApply/list";

                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }

                var param = {
                    purchaseInvoiceOrder: $scope.condition.invoiceNo,
                    supplierName: $scope.condition.invoicePaperNo,
                    statusCode: $scope.condition.status,
                    applyName: $scope.condition.payerOrgName,
                    startTime: $scope.condition.createDateStart || null,
                    endTime: $scope.condition.createDateEnd || null,
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                };

                $scope.editList = []; // 首页列表 是否可编辑
                $scope.delList = []; // 首页列表 是否可删除
                $scope.auditList = []; // 首页列表 是否可审核

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        if (item.status == 0) {
                            $scope.editList.push(true)
                            $scope.delList.push(true)
                            $scope.auditList.push(true)
                        }
                        if (item.status == 1) {
                            $scope.editList.push(false)
                            $scope.delList.push(false)
                            $scope.auditList.push(false)
                        }
                        if (item.status == 2) {
                            $scope.editList.push(true)
                            $scope.delList.push(true)
                            $scope.auditList.push(false)
                        }

                        item.createTime = $filter("YbDate")(item.createTime, df);
                        item.returnTime = $filter("YbDate")(item.returnTime, df);
                        item.createDateF = $filter("YbDate")(item.createDate, df);
                        item.signDateF = $filter("YbDate")(item.signDate, df);
                        item.isChecked = false;
                        item.signState = item.isSign === 1 ? "已签收" : "未签收";
                        item.status = item.status == 0 ? "未审核" : (item.status == 1 ? "审核通过" : "审核拒绝");



                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function initData() {
                $scope.markInfo.allChecked = false;
            }

            /*********************** 详情页开始 ***********************/
            $scope.stepList = {
                curStep: 0,
                list: [{ name: '选择发货通知单' }, { name: '生成发运交接单' }]
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderObj = {
                headerInfo: {},
                materialList: [],
                totalSum: 0, // 开票总金额
                remark: "", // 开票备注
                isEdit: false, // 是否为修改
                editId: "",
                useMachineNo: '',
                createDateStart: null,
                createDateEnd: null,
                receiverName: null
            };

            $scope.editList = []; // 首页列表 是否可编辑
            $scope.delList = []; // 首页列表 是否可删除
            $scope.auditList = []; // 首页列表 是否可审核
            /**
             * 审核页信息
             */
            $scope.auditInfo = {
                id: "", // 单据ID
                status: "", // 审核状态  1 通过    2 拒绝
                auditDesc: "" // 审核备注
            }
            //新增时左侧列表配置项
            $scope.addLeftTableConfig = {
                scrollWidth: 700,
                fixedWidth: 40,
                tableCol: [
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "type",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "订单号",
                        dataField: "purchaseBillNo",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "单据号",
                        dataField: "purchaseOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialName",
                        width: 170,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "入库数量",
                        dataField: "realAmount",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "price",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    }
                ]
            };

            $scope.newTbConf = {
                scrollWidth: 750,
                tableCol: [{
                        name: "单据类型",
                        width: 150,
                        dataField: "type",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单号",
                        width: 150,
                        dataField: "purchaseBillNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单据号",
                        width: 200,
                        dataField: "purchaseOrder",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 120,
                        dataField: "materialName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "realAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 150,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已开票数量",
                        dataField: "invoicesIssued",
                        width: 100,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可开票数量",
                        dataField: "allowNum",
                        width: 100,
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次开票数量",
                        width: 150,
                        dataField: "invoiceNum",
                        input: true,
                        inputType: "txt"
                    },
                    {
                        name: "本次开票金额",
                        width: 150,
                        dataField: "currentMoney",
                        input: false,
                        txtType: "negativeNum"
                    },

                ]
            };
            /**
             *  审核table
             */
            $scope.auditTbConf = {
                scrollWidth: 750,
                tableCol: [{
                        name: "单据类型",
                        width: 150,
                        dataField: "type",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "订单号",
                        width: 150,
                        dataField: "purchaseBillNo",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "单据号",
                        width: 200,
                        dataField: "purchaseOrder",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "零件中文名",
                        width: 120,
                        dataField: "materialName",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "realAmount",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "单价",
                        width: 150,
                        dataField: "price",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "已开票数量",
                        width: 100,
                        dataField: "invoicesIssued",
                        input: false,
                        inputType: "num",
                        negativeTxt: false
                    },
                    {
                        name: "可开票数量",
                        width: 100,
                        dataField: "allowNum",
                        input: false,
                        inputType: "",
                        negativeTxt: false
                    },
                    {
                        name: "本次开票数量",
                        width: 150,
                        dataField: "invoiceNum",
                        input: false,
                        inputType: "",
                        negativeTxt: false,
                    },
                    {
                        name: "本次开票金额",
                        width: 150,
                        dataField: "currentMoney",
                        input: false,
                        negativeTxt: true,
                        txtType: "negativeNum"
                    }
                ]
            };

            /*********************** 详情页结束 ***********************/

            $scope.sign = function (id) {
                var service = "device";
                var reqUrl = "/invoice/sign";
                ybWidget.ShowConfirm("确定要签收吗？", "签收说明").then(function (note) {
                    var param = {
                        id: id,
                        signNote: note
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };

            $scope.tabFlag = {};

            /**
             *  修改
             */
            $scope.edit = function (item) {
                $scope.changeTab(1);
                $scope.stepList.curStep = 1;
                $scope.tabFlag.type = 1;
                $scope.orderObj.isEdit = true;
                $scope.orderObj.editId = item.id;

                getItemDetail(item.id);

            };

            /**
             *  获取列表详情
             */
            function getItemDetail(id) {
                var service = "device";
                var reqUrl = "/purchaseInvoiceApply/detail?invoiceApplyId=" + id;
                ybHttp.Get(service, reqUrl, "").then(function (resp) {
                    $scope.orderObj.remark = resp.value.remark;
                    $scope.orderObj.materialList = resp.value.materials;
                    $scope.orderObj.supplierName = resp.value.supplierName;
                    $scope.orderObj.purchaseOrgName = resp.value.supplierName;
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        item.allowNum = item.realAmount - item.invoicesIssued;
                        if (item.type == 1) {
                            item.currentMoney = (item.price * item.invoiceNum * -1).toFixed(2);
                        } else {
                            item.currentMoney = (item.price * item.invoiceNum).toFixed(2);
                        }
                        item.invoiceNum = item.invoiceNum;
                        item.type = item.type == 0 ? "采购入库单" : "-";
                    });
                    getAllMoney();
                    $scope.purchaseInvoiceInfo = resp.value;
                });
            };

            /**
             *  添加开票申请
             */
            $scope.saveShenQing = function () {
                var list = [];
                angular.forEach($scope.orderObj.materialList, function (item) {
                    var obj = {};
                    obj.id = item.id;
                    obj.invoiceNum = item.invoiceNum == null || item.invoiceNum == "" ? 0 : item.invoiceNum;
                    obj.orderType = item.type == '采购入库单' ? 0 : 1;
                    list.push(obj)
                });



                if ($scope.orderObj.isEdit) {
                    // 修改
                    var param = {
                        id: $scope.orderObj.editId,
                        materiels: list,
                        remark: $scope.orderObj.remark,
                        supplierOrgId: $scope.orderObj.purchaseOrgId
                    }
                    var service = "device";
                    var reqUrl = "/purchaseInvoiceApply/updateApply";
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return false;
                        }
                        getDataList();
                        $scope.changeTab(0);
                        $scope.orderObj.isEdit = false;
                    });
                } else {
                    // 添加
                    var param = {
                        materiels: list,
                        remark: $scope.orderObj.remark,
                        supplierOrgId: $scope.orderObj.purchaseOrgId
                    }
                    var service = "device";
                    var reqUrl = "/purchaseInvoiceApply/addApply";
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return false;
                        }
                        getDataList();
                        $scope.changeTab(0);
                    });

                }

            };

            $scope.del = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/purchaseInvoiceApply/deleteApply?invoiceApplyId=" + item.id;
                    var obj = {};
                    obj.invoiceApplyId = item.id;
                    ybHttp.Post(service, reqUrl, "").then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "supplier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseOrgName = data.companyName;
                    $scope.orderObj.purchaseOrgId = data.supplierOrgId;
                })
            };

            $scope.searchAddress = function () {
                if ($scope.orderObj.purchaseOrgName == undefined) {
                    ybWidget.ShowMessage("请选择客户", MESG_TYPE.Error);
                } else {
                    getSQDataList();
                }
            };

            function getSQDataList(curPage) {
                if ($scope.orderObj.purchaseOrgId == undefined) {
                    ybWidget.ShowMessage("需要选择供货商名称", MESG_TYPE.Error);
                    return;
                }

                $scope.markInfo.curRow = -1;

                var startTime;
                var endTime;
                if ($scope.orderObj.startTime) {
                    startTime = $filter('YbDate')($scope.orderObj.startTime, "yyyy-MM-dd HH:mm:ss");
                } else {
                    startTime = undefined;
                }
                if ($scope.orderObj.endTime) {
                    endTime = $filter('YbDate')($scope.orderObj.endTime, "yyyy-MM-dd HH:mm:ss");
                } else {
                    endTime = undefined;
                }

                var service = "device";
                var reqUrl = "/purchaseInvoiceApply/applyList";

                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }

                var param = {
                    supplierOrgId: $scope.orderObj.purchaseOrgId,
                    type: $scope.orderObj.type,
                    purchaseInboundOrder: $scope.orderObj.purchaseInboundOrder,
                    startTime: startTime,
                    endTime: endTime,
                    pageSize: $scope.orderPageInfo.pageSize,
                    pageNum: $scope.orderPageInfo.curPage
                };

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.type = item.type == 0 ? "采购入库单" : "-";
                        item.orderDateF = $filter("YbDate")(item.orderDate, df);
                        item.postDateF = $filter("YbDate")(item.postDate, df);
                        item.createDateF = $filter("YbDate")(item.createDate, df);
                        item.signDateF = $filter("YbDate")(item.signDate, df);
                        item.isChecked = false;
                        item.signState = item.isSign === 1 ? "已签收" : "未签收";
                        var index = $scope.orderObj.materialList.findIndex((function (item2) {
                            return item2.id == item.id
                        }))
                        if (index == -1) {
                            item.isChecked = false;
                            $scope.markInfo.allChecked = false;
                        } else {
                            item.isChecked = true;
                        }
                    });

                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            };

            $scope.datePickerFlag = [false, false];

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                    $scope.condition.createDateStart = $filter("YbDate")($scope.condition.createDateStart, 'yyyy-MM-dd');
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                    $scope.condition.createDateEnd = $filter("YbDate")($scope.condition.createDateEnd, 'yyyy-MM-dd');
                }
                if (!!timeFormatObj.tStart && !!timeFormatObj.tEnd && (timeFormatObj.tEnd < timeFormatObj.tStart)) {
                    ybWidget.ShowMessage("起止时间不能大于结束时间", MESG_TYPE.Error)
                    $scope.condition.createDateStart = null;
                    $scope.condition.createDateEnd = null;
                }
            };

            // 新增开票申请
            $scope.updateSAP = function () {
                $scope.changeTab(1);
                $scope.stepList.curStep = 0;
                $scope.orderObj.isEdit = false;
                $scope.orderObj.type = '0';
                $scope.orderObj.materialList = [];
                $scope.orderObj.purchaseOrgName = "";
                $scope.orderDataList = [];
            };

            /**
             *  开票申请 下一步
             */
            $scope.nextStep = function () {
                $scope.orderObj.totalSum = 0;
                $scope.stepList.curStep = 1;
                angular.forEach($scope.orderObj.materialList, function (item) {
                    item.allowNum = item.realAmount - item.invoicesIssued;
                    item.invoiceNum = item.allowNum;
                    $scope.checkStock(item);
                });

                $scope.orderObj.remark = null;
            };

            /**
             *  开票申请 上一步
             */
            $scope.upStep = function () {
                $scope.stepList.curStep = 0;
                angular.forEach($scope.orderDataList, function (items) {
                    items.isChecked = false;
                    $scope.markInfo.allChecked = true;
                    angular.forEach($scope.orderObj.materialList, function (item) {
                        if (items.id == item.id) {
                            items.isChecked = true;
                        } else {
                            $scope.markInfo.allChecked = false;
                        }
                    });
                })
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            /**
             *  审核按钮
             */
            $scope.shenHeSAP = function (obj) {
                $scope.auditInfo.auditDesc = '';
                $scope.changeTab(2);
                $scope.auditInfo.id = obj.id;
                getItemDetail(obj.id);
            };

            /**
             *  详情
             */
            $scope.getDetailInfo = function (obj) {
                $scope.changeTab(3);
                getItemDetail(obj.id);
            };

            /**
             *  审核结果
             */
            $scope.auditPurchase = function (val) {
                if (val == 2) {
                    if ($scope.auditInfo.auditDesc == "") {
                        ybWidget.ShowMessage("审核拒绝必需输入审核意见", MESG_TYPE.Error);
                        return;
                    }
                }
                var param = {
                    invoiceApplyId: $scope.auditInfo.id,
                    statusCode: val,
                    suggestion: $scope.auditInfo.auditDesc
                };
                var service = "device";
                var reqUrl = "/purchaseInvoiceApply/examine";
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                })

            };

            (function () {
                if ($scope.isZHJCH) {
                    var newTableConfig = angular.copy($scope.tableConfig);
                    $scope.tableConfig.scrollWidth = 1540;
                    $scope.tableConfig.tableCol = [];
                    angular.forEach(newTableConfig.tableCol, function (item) {
                        if (item.type !== 'operate') {
                            $scope.tableConfig.tableCol.push(angular.copy(item));
                        }
                    });
                }

                getDataList(1);
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);